题目链接:点击打开链接
题意:见链接。(中文题)
思路:该题与普通并查集的不同之处在于,需要查询两个点最早联通的时刻。 我们不妨在结点上维护一些信息:假设结点v, 那么维护ans[v]表示v到父亲结点的时间。 然后查询的时候, 考虑到并查集是一个树形结构, 如果两个顶点联通, 两个顶点之间有唯一路径, 路径上边的最大值就是了。
因为要维护这个关系, 所以显然不能路径压缩, 因为那样会破坏结构, 为了使得树不会退化成一条长长的链, 我们可以按秩合并, 可以证明, 这样最大树高logn, 所以单组查询的复杂度是logn。 总的复杂度是mlogn
细节参见代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int mod = 1000000000 + 7;
const int INF = 1000000000;
const int maxn = 100005;
int T,n,m,fa[maxn],ra[maxn],ans[maxn],vis[maxn];
void init() {
for(int i=1;i<=n;i++) {
fa[i] = i;
ra[i] = 0;
ans[i] = 0;
vis[i] = -1;
}
}
int _find(int x) { return fa[x] == x ? x : _find(fa[x]); }
bool Union(int u, int v, int t) {
int x = _find(u), y = _find(v);
if(x == y) return false;
if(ra[x] > ra[y]) {
fa[y] = x;
ans[y] = t;
}
else {
fa[x] = y;
ans[x] = t;
if(ra[x] == ra[y]) ra[y]++;
}
return true;
}
int query(int u, int v) {
int x = _find(u), y = _find(v);
if(x != y) return 0;
int p = u, now = 0, res = 0;
while(true) {
vis[p] = now;
if(fa[p] == p) break;
now = max(now, ans[p]);
p = fa[p];
}
now = 0;
p = v;
while(true) {
if(vis[p] >= 0) { res = max(now, vis[p]); break; }
if(fa[p] == p) break;
now = max(now, ans[p]);
p = fa[p];
}
p = u;
while(true) {
vis[p] = -1;
if(fa[p] == p) break;
p = fa[p];
}
return res;
}
int main() {
scanf("%d",&T);
while(T--) {
scanf("%d%d",&n,&m);
init();
int last = 0, cnt = n, id, u, v;
for(int i=1;i<=m;i++) {
scanf("%d%d%d",&id,&u,&v);
u ^= last; v ^= last;
if(id == 0) {
if(Union(u, v, i)) --cnt;
printf("%d\n",last = cnt);
}
else {
printf("%d\n",last = query(u, v));
}
}
}
return 0;
}